package com.longrise.android.byjk.plugins.course.batchbuy;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.AllCourseChildBean;
import com.longrise.android.byjk.model.AllCourseParentBean;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.PrintLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Locale.CHINESE;

/**
 * Created by callxkj on 2017/11/17.
 * 批量购买
 */

public class BatchbuyPresenter extends BatchbuyContract.presenter {

    private static final String TAG = "BatchbuyPresenter";
    private List<AllCourseParentBean> mParentBeanList = new ArrayList<>();
    private Map<String, List<AllCourseChildBean>> mChildMap = new HashMap<>();
    private ArrayList<Integer> mBuycountList = new ArrayList<>();
    private Map<Integer, Double> mDiscountrateMap = new HashMap<>();

    @Override
    protected void init() {
        getSortFromNet();
        getTipsAndDiscount();
    }


    /**
     * 获取课程分类列表
     */
    public void getSortFromNet() {
        EntityBean bean = new EntityBean();
        bean.set("areaid", "0");  //以前保宝的全国课程
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService2("", UrlConstants.BaseUrl,
                "bbt_course_sAllTrainPlanAssortmentsBean", fbean, new LoadDataManager.OnRequestCallListener2() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        parseSortData(result);
                    }

                    @Override
                    public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {

                    }

                    @Override
                    public void onFinished(String key, String service) {
                        DZZWTools.dismissDialog(null);
                    }
                });
    }

    /**
     * 解析课程分类
     *
     * @param result
     */
    public void parseSortData(Object result) {
        try {
            if (result != null) {
                EntityBean bean = (EntityBean) result;
                Integer resultstate = bean.getInt("resultstate");
                if (resultstate == 1) {
                    EntityBean resultBean = bean.getBean("result");
                    boolean isshowtips = resultBean.getBoolean("isshowtips");
                    if (isshowtips) {  //是否可以购买 不支持购买的显示提示
                        String tips = resultBean.getString("tips");
                    } else {
                        EntityBean[] results = resultBean.getBeans("assortment");
                        if (results != null) {
                            for (EntityBean resultbean : results) {
                                String assortmentname = resultbean.getString("assortmentname");
                                String assortmenttype = resultbean.getString("assortmenttype");
                                AllCourseParentBean courseBean = new AllCourseParentBean();
                                courseBean.setAssortmentname(assortmentname);
                                courseBean.setAssortmenttype(assortmenttype);
                                mParentBeanList.add(courseBean);
                            }
                            mView.initFirstAdapter(mParentBeanList);
                        } else {

                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取每个系统下面的 课程数据
     */
    public void loadAdapter2Data(final String traintype) {
        if (mChildMap.containsKey(traintype)) {
            List<AllCourseChildBean> allCourseChildBeen = mChildMap.get(traintype);
            mView.refreshSecondAdapter(allCourseChildBeen);
        } else {
            String usersfzh = UserInfor.getInstance().getUsersfzh();
            EntityBean bean = new EntityBean();
            bean.set("assortmenttype", traintype);
            bean.set("areaid", "0");
            bean.set("cardno", usersfzh);
            EntityBean fbean = new EntityBean();
            fbean.set("bean", bean);
            mView.showLoadingDialog();
            LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                    "bbt_buys_sAllTrainPlanBeans", fbean, new LoadDataManager.OnRequestCallListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            parseAllTrainData(traintype, result);
                        }

                        @Override
                        public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                            mView.showNonNetPage();
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            mView.dismissLoadingDialog();
                        }
                    });

        }
    }

    /**
     * 解析每个系统下面的 课程数据
     */
    private void parseAllTrainData(String traintype, Object result) {
        try {
            if (result != null) {
                EntityBean bean = (EntityBean) result;
                int resultstate = bean.getInt("resultstate");
                if (resultstate == 1) {
                    List<AllCourseChildBean> childBeanList = new ArrayList<>();
                    EntityBean[] results = bean.getBeans("result");
                    if (results != null && results.length != 0) {
                        for (EntityBean resultBean : results) {
                            AllCourseChildBean childBean = new AllCourseChildBean();
                            childBean.setRealpic(resultBean.getString("realpic"));
                            childBean.setSignupendtime(resultBean.getString("signupendtime"));
                            childBean.setGrouptype(resultBean.getString("grouptype"));
                            childBean.setGrouptypename(resultBean.getString("grouptypename"));
                            childBean.setCoursetype(resultBean.getString("coursetype"));
                            childBean.setCoursetypename(resultBean.getString("coursetypename"));
                            childBean.setCourseid(resultBean.getString("courseid"));
                            childBean.setName(resultBean.getString("name"));
                            childBean.setOriginprice(resultBean.getString("originprice"));
                            childBean.setRealprice(resultBean.getString("realprice"));
                            childBean.setGrouptime(resultBean.getString("grouptime"));
                            childBean.setCwtype(resultBean.getString("cwtype", ""));
                            childBeanList.add(childBean);
                        }
                    }
                    mChildMap.put(traintype, childBeanList);
                    mView.refreshSecondAdapter(childBeanList);
                } else {
                    mView.showToast(bean.getString("resultdesc"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取页面下面的提示语 和 折扣率
     */
    private void getTipsAndDiscount() {
        EntityBean bean = new EntityBean();
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mView.showNormalLoadingPage();
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_pay_searchAllDiscount", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            if (result != null) {
                                EntityBean bean = (EntityBean) result;
                                int resultstate = bean.getInt("resultstate");
                                if (resultstate == 1) {
                                    EntityBean resultBean = bean.getBean("result");
                                    parseTipsAndDiscount(resultBean);
                                    mView.showContentPage();
                                } else {
                                    String resultdesc = bean.getString("resultdesc");
                                    mView.showToast(resultdesc);
                                    mView.showNonNetPage();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.showNonNetPage();
                        }
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        mView.showNonNetPage();
                    }

                    @Override
                    public void onFinished(String key, String service) {

                    }
                });
    }

    /**
     * 解析折扣率 和 tips
     */
    private void parseTipsAndDiscount(EntityBean bean) {
        String[] discountstr = (String[]) bean.get("discountstr");
        mView.showTips(discountstr);  //显示tips

        EntityBean[] discountlists = bean.getBeans("discountlist");
        mBuycountList.clear();
        mDiscountrateMap.clear();
        for (int x = 0; x < discountlists.length; x++) {
            EntityBean discountBean = discountlists[x];
            Integer buycount = discountBean.getInt("buycount");
            Double discountrate = discountBean.getDouble("discountrate");
            mBuycountList.add(buycount);
            mDiscountrateMap.put(buycount, discountrate);
        }
        mBuycountList.add(0, 0); //第一个位置添加一个购买课程数量为0
        mDiscountrateMap.put(0, 1.0); //购买课程为0的话 费率为1
        Collections.sort(mBuycountList);
        calculatePrice(null);
    }

    /**
     * 计算折扣率 价格
     */
    @Override
    public void calculatePrice(List<AllCourseChildBean> selectedCourseBeans) {
        double discountrate = 1;
        if (selectedCourseBeans != null && selectedCourseBeans.size() > 0) {
            int courseNum = selectedCourseBeans.size(); //选择的课程数量
            int currentBuycount = 0;
            for (int x = 0; x < mBuycountList.size(); x++) {
                int buycount = mBuycountList.get(x);
                if (x == mBuycountList.size() - 1) { //循环到最后一个还没有符合的 就取最后一个
                    if(courseNum < buycount){
                        currentBuycount = mBuycountList.get(x - 1);
                    }else{
                        currentBuycount = buycount;
                    }
                    break;
                }
                if (courseNum >= buycount) {
                    continue;
                } else {
                    currentBuycount = mBuycountList.get(x - 1);
                    break;
                }

            }
            //折扣率
            discountrate = mDiscountrateMap.get(currentBuycount);
            double totalPrice = 0;
            for (int i = 0; i < selectedCourseBeans.size(); i++) {
                AllCourseChildBean allCourseChildBean = selectedCourseBeans.get(i);
                String realpricestr = allCourseChildBean.getRealprice();
                totalPrice = Double.parseDouble(realpricestr) + totalPrice;
            }
            //打折后的总价格
            String discountratePrice = String.format(CHINESE, "%.2f", totalPrice * discountrate);
            //课程原来的总价
            String totalPricestr = String.format(CHINESE, "%.2f", totalPrice);
            //左下角的提示
            String discountPriceDesc = "";
            //左下角显示 折扣价 或者 实付款
            String zhj = "";
            if (discountrate == 1) { //没有打折
                Integer firstNum = mBuycountList.get(1); //第一个打折阶段  需要购买课程的数量;
                String firstdiscountrate = String.format(CHINESE, "%.1f", mDiscountrateMap.get(firstNum) * 10);
                firstdiscountrate = subZeroAndDot(firstdiscountrate);
                int needNum = firstNum - selectedCourseBeans.size();
                discountPriceDesc = "再选" + needNum + "节课程，享受" + firstdiscountrate + "折优惠";
                zhj = "实付款：";
            } else {
                String discountratestr = String.format(CHINESE, "%.1f", discountrate * 10);
                discountratestr = subZeroAndDot(discountratestr);
                discountPriceDesc = "总价¥" + totalPricestr + "，" + discountratestr + "折优惠";
                zhj = "折后价：";
            }

            mView.showDiscountratePrice(true, String.valueOf(selectedCourseBeans.size()),
                    discountratePrice, discountPriceDesc, zhj);

        } else {
            //没有选择课程
            mView.showDiscountratePrice(false, null, null, null, null);
        }

    }


    /**
     * 去掉后面多余的0
     */
    public String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

}
